package com.c2b.algorithm.leetcode.base.backtracking;

import java.util.*;

/**
 * <a href='https://leetcode.cn/problems/permutations-ii/description/'>全排列 II(Permutations II)</a>
 * <p>给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。</p>
 * <p>你可以按 任何顺序 返回答案。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：nums = [1,1,2]
 *      输出：
 *      [[1,1,2],
 *       [1,2,1],
 *       [2,1,1]]
 *
 * 示例 2：
 *      输入：nums = [1,2,3]
 *      输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= nums.length <= 8</li>
 *         <li>-10 <= nums[i] <= 10</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/26 16:39
 */
public class LC0047Permutations_II_M {

    static class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {

            List<List<Integer>> retList = new ArrayList<>();
            int length;
            if (nums == null || (length = nums.length) == 0) {
                return retList;
            }
            Arrays.sort(nums);
            dfs(nums, length, new boolean[length], new ArrayDeque<>(length), retList);
            return retList;
        }

        private void dfs(int[] nums, int remainCount, boolean[] used, Deque<Integer> path, List<List<Integer>> retList) {
            if (remainCount == 0) {
                retList.add(new ArrayList<>(path));
                return;
            }
            for (int i = 0; i < nums.length; i++) {
                if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                    continue;
                }
                if (!used[i]) {
                    used[i] = true;
                    path.add(nums[i]);
                    dfs(nums, remainCount - 1, used, path, retList);
                    used[i] = false;
                    path.removeLast();
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        for (List<Integer> list : solution.permuteUnique(new int[]{1, 1, 2})) {
            for (Integer integer : list) {
                System.out.print(integer + "  ");
            }
            System.out.println();

        }
    }
}
